package com.aplink.dellcommercial.fragments;

import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;

import com.aplink.dellcommercial.R;
import com.aplink.dellcommercial.configuration.DellController;
import com.aplink.dellcommercial.database.DellDataTable;
import com.aplink.dellcommercial.webservices.DataResult;
import com.aplink.dellcommercial.webservices.Methods;
import com.aplink.dellcommercial.webservices.WebServiceHelper;
import com.aplink.generic.GenericFragment;
import com.aplink.generic.constant.HandlerConstant;
import com.aplink.generic.dialog.GenericAlertDialog;
import com.aplink.generic.handler.IHandleMessage;
import com.aplink.generic.network.DownloadManager;
import com.aplink.generic.pojo.GenericObject;
import com.aplink.generic.pojo.controlspec.ControlSpec;
import com.aplink.generic.pojo.controlspec.MenuSpec;
import com.aplink.generic.util.Utility;

import java.io.File;
import java.util.ArrayList;

public class PriceBookFragment extends GenericFragment implements
        IHandleMessage {

    private ArrayList<GenericObject> genericObjects;

    @Override
    protected void onHandleOptionMenuClickEvent( MenuSpec.MenuItem menuItem ) {
        final String validationGroup = menuItem.getValidationgroup();
        if ( validationGroup.equals( "get_lastest_pricebook" ) ) {
            if ( DellController.isOnline() ) {
                WebServiceHelper.getInstance().getPriceBook( getActivity(),
                        this.getHandler(), getObjPropList() );
            } else {
                Toast.makeText( this.getApplicationContext(),
                        "Please check your connection!", Toast.LENGTH_SHORT )
                        .show();
            }
        }
    }

    @Override
    protected void handleSelectedItemEvent( AdapterView<?> adapter, View v,
                                            int position ) {
        super.handleSelectedItemEvent( adapter, v, position );
        ControlSpec controlSpec = (ControlSpec) adapter.getTag();
        String validaitonGroup = controlSpec.getValidationGroup();
        if ( validaitonGroup.equalsIgnoreCase( "submit" ) ) {
            String selectedValue = (String) adapter.getItemAtPosition( position );
            changeSelection( selectedValue );
        }
    }

    private void changeSelection( String value ) {
        getCustomGallery().filter( value );
    }

    @Override
    public void onActivityCreated( Bundle savedInstanceState ) {
        super.onActivityCreated( savedInstanceState );
        this.initData();
        this.loadDataToForm();
        this.getHandler().setHandleMessage( this );
    }

    @Override
    public void onHandleMessage( Message msg ) {
        if ( msg.what == HandlerConstant.HTTP_TASK_RESULT ) {
            final DataResult result = (DataResult) msg.obj;
            this.downloadImagePricebook( result );
        } else if ( msg.what == HandlerConstant.DOWNLOAD_FILE_RESULT ) {
            insertPromotionToDatabase( msg.obj );
        }
    }

    @SuppressWarnings("unchecked")
    private void insertPromotionToDatabase( Object obj ) {
        ArrayList<String> arrayList = (ArrayList<String>) obj;
        if ( genericObjects.size() != arrayList.size() ) {
            return;
        }
        String currentDatetime = Utility.getDateTime();
        for ( int i = 0 ; i < genericObjects.size() ; i++ ) {
            String localPath = arrayList.get( i );
            genericObjects.get( i ).setContentByAttributeName( "ImageLocalPath",
                    localPath );
            genericObjects.get( i ).setContentByAttributeName( "DownloadedTime",
                    currentDatetime );
            this.getDBHelper().insert( genericObjects.get( i ), getObjPropCol() );
        }
        this.loadDataToForm();
    }

    @SuppressWarnings("unchecked")
    private void downloadImagePricebook( DataResult result ) {
        if ( result.getMethodName().equals( Methods.GET_PRICEBOOK ) ) {
            genericObjects = (ArrayList<GenericObject>) result.getData();
            ArrayList<String> physicalPaths = new ArrayList<String>();

            File storagePath = new File(
                    Environment.getExternalStorageDirectory(), "SellProff" );
            storagePath.mkdirs();
            if ( genericObjects != null ) {
                for ( GenericObject genericObject : genericObjects ) {
                    boolean isPromotionExists = this.getDBHelper().isExists(
                            genericObject, getObjPropCol() );
                    if ( ! isPromotionExists ) {
                        String physicalPath = (String) genericObject
                                .getGenericAttributeFromObjectMappingName(
                                        "PhysicalPath" ).getValue();
                        physicalPaths.add( physicalPath );
                    }
                }

                if ( physicalPaths.size() > 0 ) {
                    DownloadManager downloadManager = new DownloadManager(
                            getActivity(), getHandler(), storagePath.toString() );
                    downloadManager.execute( physicalPaths
                            .toArray( new String[physicalPaths.size()] ) );
                } else {
                    GenericAlertDialog.newInfoDialog( getActivity(),
                            getString( R.string.dell__latest_pricebook ),
                            getString( R.string.dell__dialog_info ) ).show();
                }
            } else {
                GenericAlertDialog.newInfoDialog( getActivity(),
                        getString( R.string.dell__no_pricebook ),
                        getString( R.string.dell__dialog_info ) ).show();
            }
        }
    }

    public ArrayList<GenericObject> getGenericObjects() {
        return genericObjects;
    }

    public void setGenericObjects( ArrayList<GenericObject> genericObjects ) {
        this.genericObjects = genericObjects;
    }

    @Override
    protected void onHandleControlClickEvent( ControlSpec controlSpec ) {

    }

    @Override
    public int getContentView() {
        return R.layout.aplink_dellcommercial_new_promotion_activity;
    }

    @Override
    public int getFormDesign() {
        return R.raw.form_design_pricebook;
    }

    @Override
    public int getContentData() {
        return R.raw.content_data_pricebook;
    }

    @Override
    public String getTable() {
        return DellDataTable.ImagePricebook.TABLE_NAME;
    }
}
